package com.fengke.portal.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.fengke.portal.config.HostConfig;
import com.fengke.util.Constants;
import com.fengke.util.LoggerFactory;

/**
 * Servlet Filter implementation class XSSFilter
 */
public class XSSFilter implements Filter {
	private Logger logger = LoggerFactory.getLogger(XSSFilter.class);

	private String[] illegalString = { /*"<", ">",*/ "&#", "\"", "\'", "\\", "\r", "\n" };

	/**
	 * Default constructor.
	 */
	public XSSFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws IOException, ServletException {
		request1.setCharacterEncoding("UTF-8");
		HttpServletRequest request = (HttpServletRequest) request1;
		HttpServletResponse response = (HttpServletResponse) response1;
		@SuppressWarnings("unchecked")
		Enumeration<String> enumString = request.getParameterNames();

		boolean containsIllegal = false;
		while (enumString.hasMoreElements()) {
			String s = enumString.nextElement();
			String[] sv = request.getParameterValues(s);
			if (sv != null) {
				for (int i = 0; i < sv.length; i++) {
					for (int j = 0; j < illegalString.length; j++) {
						if (sv[i].contains(illegalString[j])) {
							containsIllegal = true;
							logger.info("request.parameterValue = [" + sv[i] + "]; illegalString = [" + illegalString[j] + "]");
							break;
						}
					}
				}
			}
		}
		HostConfig hostConfig = (HostConfig) request.getSession().getServletContext().getAttribute("hostConfig");
		if (containsIllegal) {
			request.getSession().setAttribute(Constants.SESSION_ERROR_MSG, "请求中包含非法信息");
			RequestDispatcher dispatcher = request.getRequestDispatcher(hostConfig.getPortalHost() + "jsp/include/error.jsp");
			dispatcher.forward(request, response);
			return;
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
